#include <REGX52.H>
#include "INTRINS.H"
#include "SPI.h"


sbit SPI_MISO=P0^2;
sbit SPI_MOSI=P0^0;
sbit SPI_CLK=P0^1;
sbit SPI_CS=P0^3;

unsigned char SPI_Mode=SPI_Mode_0;

void SPI_SetMode(unsigned char Mode)
{
    SPI_Mode=Mode;
    switch (Mode)
    {
    case SPI_Mode_0:
    case SPI_Mode_1:
        SPI_CLK=0;
        break;
    case SPI_Mode_2:
    case SPI_Mode_3:
        SPI_CLK=1;
        break;
    }
}

void SPI_Init(unsigned char Mode)
{
    SPI_CS=0;
    SPI_MOSI=0;
    SPI_MISO=1;
    SPI_CS=1;
    SPI_SetMode(Mode);
}

unsigned char SPI_TransFer(unsigned char Data)
{
    unsigned char i;
    unsigned char Receive=0;
    for(i=0;i<8;i++)
    {
        if (SPI_Mode == SPI_Mode_0 || SPI_Mode == SPI_Mode_2) // 模式0和2：在第一个时钟边沿采样数据
        {
            SPI_MOSI=(Data&0x80)?1:0;
            Data<<=1;

            if(SPI_Mode==SPI_Mode_0)
            {
                SPI_CLK=1;
            }
            else
            {
                SPI_CLK=0;
            }
            _nop_();_nop_();

            Receive<<=1;
            if(SPI_MISO==1)
            {
                Receive|=0x01;
            }

            if (SPI_Mode == SPI_Mode_0)
            {
                SPI_CLK = 0;
            }
            else
            {
                SPI_CLK = 1;
            }
        }
        else
        {
            if (SPI_Mode == SPI_Mode_1)
            {
                SPI_CLK = 1;
            }
            else
            {
                SPI_CLK = 0;
            }
            _nop_();
            _nop_();
            SPI_MOSI = (Data & 0x80) ? 1 : 0;
            Data <<= 1;

            if (SPI_Mode == SPI_Mode_1)
            {
                SPI_CLK = 0;
            }
            else
            {
                SPI_CLK = 1;
            }

            Receive <<= 1;
            if (SPI_MISO == 1)
            {
                Receive |= 0x01;
            }

        }
    }
   return Receive;
}

void SPI_CS_Enable()
{
    SPI_CS=0;
}

void SPI_CS_Disable()
{
    SPI_CS=1;
}